package com.dnjn.happiness.biz.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.biz.service.ICommunicateService;
import com.dnjn.happiness.biz.service.IHistoryInterviewService;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.SysPostVO;
import com.dnjn.happiness.common.core.model.SysSiteVO;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.emo.api.RemoteEmoUserService;
import com.dnjn.happiness.system.api.RemoteConfigService;
import com.dnjn.happiness.system.api.RemoteDeptService;
import com.dnjn.happiness.system.api.RemotePostService;
import com.dnjn.happiness.system.api.RemoteRoleService;
import com.dnjn.happiness.system.api.RemoteSiteService;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysRole;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.system.api.model.TeamTreeSelectVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Tag(name = "biz team 团队接口", description = "团队接口")
@RestController
@RequestMapping("/team")
public class TeamController {
    private static final Logger log = LoggerFactory.getLogger(TeamController.class);
    @Autowired
    protected ICommunicateService communicateService;
    @Autowired
    private RemoteUserService userService;
    @Autowired
    private RemoteDeptService deptService;
    @Autowired
    private RemoteConfigService configService;
    @Autowired
    private RemoteEmoUserService emoUserService;
    @Autowired
    private RemoteSiteService siteService;
    @Autowired
    private IHistoryInterviewService historyInterviewService;
    @Autowired
    private RemoteRoleService roleMapper;
    @Autowired
    private RemotePostService postService;

    @Operation(summary = "上级信息")
    @GetMapping("/getSuper")
    public AjaxResult getSuper() {
        Long userId = SecurityUtils.getUserId();
        AjaxResult ajax = AjaxResult.success();
        //查询是否开启对上级评价 biz.appraise.superior.enabled
        String flag = "";
        R<String> result = configService.configKeyApi("biz.appraise.superior.enabled", SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            flag = result.getData();
        }
        if ("true".equals(flag)) {
            ajax.put("isEvaluate", "true");
        } else {
            ajax.put("isEvaluate", "false");
        }
        return ajax;


    }




    /**
     * 查询普通用户的团队个人信息
     */
    @Operation(summary = "查询普通用户的团队个人信息")
    @GetMapping("/getCommonUserInfo")
    public AjaxResult getCommonUserInfo() {
        Long userId = SecurityUtils.getUserId();
        SysUser user = new SysUser();
        R<SysUser> result = userService.selectUserById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            user = result.getData();
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        return ajax;
    }


    /**
     * 搜索名称 显示上级名称+用户名称
     */
    @Operation(summary = "搜索名称")
    @GetMapping("/getUserByNickName/{nickName}")
    public AjaxResult getUserByNickName(@PathVariable String nickName) {
        if (StringUtils.isEmpty(nickName)) {
            return AjaxResult.error("用户名称不能为空!");
        }
        SysUser sysUser1 = new SysUser();
        sysUser1.setNickName(nickName);
        List<SysUser> list = new ArrayList<>();
        R<List<SysUser>> result = userService.selectUserList(sysUser1, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            list = result.getData();
        }
        AjaxResult ajax = new AjaxResult();
        if (CollectionUtils.isEmpty(list)) {
            ajax.put("userList", list);
            return ajax;
        }
        for (SysUser sysUser : list) {
            if (!ObjectUtils.isEmpty(sysUser.getDeptId()) && sysUser.getDeptId().equals(sysUser.getDept().getLeaderId())) {
                //如果当前用户为所属部门的leader，上级部门=当前部门的上级部门
                R<SysDept> resultDept = deptService.selectDeptByChildUserId(sysUser.getDeptId(), SecurityConstants.INNER);
                if (StringUtils.isNotNull(resultDept) && StringUtils.isNotNull(resultDept.getData())) {
                    sysUser.setLeaderDept(resultDept.getData());
                }
            } else {
                //如果当前用户不为所属部门的leader，上级部门=当前所属部门
                sysUser.setLeaderDept(sysUser.getDept());
            }
        }

        ajax.put("userList", list);
        return ajax;
    }

    /**
     * 总部人力查看所有厂区列表
     */
    @Operation(summary = "总部人力查询厂区列表")
    @GetMapping("/getSiteList")
    public AjaxResult getSiteList() {
        List<SysSiteVO> list = new ArrayList<>();
        R<List<SysSiteVO>> result = siteService.getSiteList(SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            list = result.getData();
        }
        return AjaxResult.success(list);
    }


    /**
     * 团队点击个人详情，查看个人信息
     */
    @Operation(summary = "团队点击个人详情查看个人信息")
    @GetMapping("/getUserInfoByUseId/{userId}")
    public AjaxResult getUserInfoByUseId(@PathVariable Long userId) {
        SysUser sysUser = new SysUser();
        R<SysUser> result = userService.selectUserAndScore(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            sysUser = result.getData();
        }
        return AjaxResult.success(sysUser);
    }


    /**
     * 根据前端传过来的厂区的部门ID去查询树列表结构
     */
//    @Operation(summary = "总部人力根据部门ID去查询树列表结构")
//    @GetMapping("/getTeamTreeByDeptId/{deptId}")
    public AjaxResult getTeamTreeByDeptId(Long deptId) {
        Assert.notNull(deptId, "deptId不能为空");
        AjaxResult ajax = new AjaxResult();
        SysDept sysDept1 = new SysDept();
        sysDept1.setDeptId(deptId);
//        List<TeamTreeSelect> treeSelectList = deptService.selectTeamTreeList(sysDept1);
        List<TeamTreeSelectVO> treeSelectList = new ArrayList<>();
        R<List<TeamTreeSelectVO>> result = deptService.getTeamTreeByDeptId(deptId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            treeSelectList = result.getData();
        }
        ajax.put("deptList", treeSelectList);
        return ajax;
    }

    /**
     * 查询当前用户下级部门团队信息 -> 系统自带的机构树
     */
    @Operation(summary = "系统自带的机构树查当前用户部门信息")
    @GetMapping("/getDetpListByUser1/{siteId}")
    public AjaxResult getDetpListByUser1(@PathVariable Long siteId) {
        //100
        SysUser currUser = null;
        R<SysUser> result = userService.selectUserById(SecurityUtils.getUserId(), SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            currUser = result.getData();
        }
        Long deptId = currUser.getDeptId();
        AjaxResult ajax = new AjaxResult();
        if (!ObjectUtils.isEmpty(deptId)) {
            if (deptId.equals(100L)) {

                Long deptId1 = null;
                R<SysSiteVO> resultSite = siteService.getInfoById(siteId, SecurityConstants.INNER);
                if (StringUtils.isNotNull(resultSite) && StringUtils.isNotNull(resultSite.getData())) {
                    deptId1 = resultSite.getData().getDeptId();
                }
                return getTeamTreeByDeptId(deptId1);
            }
        } else {
            ajax.put("sysUser", currUser);
            return ajax;
        }
        SysDept sysDept1 = new SysDept();
        List<TeamTreeSelectVO> treeSelectList = new ArrayList<>();
        R<List<TeamTreeSelectVO>> resultVo = deptService.selectTeamTreeList(sysDept1, SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultVo) && StringUtils.isNotNull(resultVo.getData())) {
            treeSelectList = resultVo.getData();
        }
        if (treeSelectList.size() > 0) {
            //如果有子部门
            ajax.put("deptList", treeSelectList);
        } else {
            SysDept sysDept = new SysDept();
            R<SysDept> resultDept = deptService.getInfoById(deptId, SecurityConstants.INNER);
            if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                sysDept = resultDept.getData();
            }
//            SysUser sysUser = userService.selectUserInfo(sysDept.getLeaderId());
//            ajax.put("sysUser", sysUser);
            ajax.put("sysUser", currUser);
            ajax.put("spuer", sysDept);
        }
        return ajax;
    }




    /**
     * 点击需沟通用户，查看需沟通用户信息
     */
    @Operation(summary = "点击详情获取用户组织机构信息")
    @GetMapping("/getDeptsByUserId/{userId}")
    public AjaxResult getDeptsByUserId(@PathVariable Long userId) {
        return AjaxResult.success(getDeptListByUserId(userId));
    }


    /**
     * 根据用户id查询当前用户得组织机构列表
     */
    public List<SysDept> getDeptListByUserId(Long userId) {
        Assert.notNull(userId, "userId不能为空!");
        SysUser user = null;
        R<SysUser> result = userService.selectUserInfo(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            user = result.getData();
        }
        Long deptId = user.getDeptId();
        List<SysDept> sysDeptList = new ArrayList<>();
        if (ObjectUtils.isEmpty(deptId)) {
            return sysDeptList;
        }
        SysDept dept = null;
        R<SysDept> resultDept = deptService.getInfoById(deptId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultDept) && StringUtils.isNotNull(resultDept.getData())) {
            dept = resultDept.getData();
        }
        String ancestors = null;
        if (dept != null) {
            ancestors = dept.getAncestors();
        }
        if (StringUtils.isEmpty(ancestors)) {
            return sysDeptList;
        }
        if (ancestors.contains(",")) {
            String[] split = ancestors.split(",");
            for (int i = 0; i < split.length; i++) {
                if (!"0".equals(split[i])) {
                    R<SysDept> reulstDept = deptService.getInfoById(Long.parseLong(split[i]), SecurityConstants.INNER);
                    if (StringUtils.isNotNull(reulstDept) && StringUtils.isNotNull(reulstDept.getData())) {
                        sysDeptList.add(reulstDept.getData());
                    }
                }
            }
        } else {
            if (!"0".equals(ancestors)) {
                R<SysDept> reulstDept = deptService.getInfoById(Long.parseLong(ancestors), SecurityConstants.INNER);
                if (StringUtils.isNotNull(reulstDept) && StringUtils.isNotNull(reulstDept.getData())) {
                    sysDeptList.add(reulstDept.getData());
                }
            }
        }
        sysDeptList.add(dept);

        return sysDeptList;
    }

    @Operation(summary = "团队需要沟通列表-新")
    @PostMapping("/getTeamCommunicateListNew")
    public AjaxResult getTeamCommunicateListNew(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size, @RequestParam(required = false) String nickName) {
        //查询当前用户下的所有员工，并且快乐值在临界值下面
        Long userId = SecurityUtils.getUserId();
        SysUser user = new SysUser();
        R<SysUser> result = userService.selectUserById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            user = result.getData();
        }
        Page page = Page.of(current, size);
        HashMap<String, Object> map = new HashMap<>();
        map.put("deptId", user.getDeptId());
        if (StringUtils.isNotEmpty(nickName)) {
            map.put("nickName", nickName);
        }
        Page<SysUser> interviewPage = historyInterviewService.getPageX(page, map);

        for (SysUser sysUser : interviewPage.getRecords()) {
            Integer communicateCount = communicateService.getCommunicateCount(sysUser.getUserId());
            sysUser.setCommunicateCount(communicateCount);
        }
        return AjaxResult.success(interviewPage);
    }

    // 后台
    @RequiresPermissions("biz:team:query")//这个没有团队 权限加到沟通里边了
    @Operation(summary = "团队需要沟通列表-新")
    @PostMapping("/getTeamCommunicateListNewAdmin")
    public AjaxResult getTeamCommunicateListNewAdmin(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size, @RequestParam(required = false) String nickName) {
        //查询当前用户下的所有员工，并且快乐值在临界值下面
        Long userId = SecurityUtils.getUserId();
        SysUser user = new SysUser();
        R<SysUser> result = userService.selectUserById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            user = result.getData();
        }
        AjaxResult ajax = AjaxResult.success();
        Page page = Page.of(current, size);
        HashMap<String, Object> map = new HashMap<>();
        map.put("deptId", user.getDeptId());
        if (StringUtils.isNotEmpty(nickName)) {
            map.put("nickName", nickName);
        }
        Page<SysUser> interviewPage = historyInterviewService.getPageX(page, map);

        for (SysUser sysUser : interviewPage.getRecords()) {
            Integer communicateCount = communicateService.getCommunicateCount(sysUser.getUserId());
            sysUser.setCommunicateCount(communicateCount);
        }
        return AjaxResult.success(interviewPage);
    }

    /**
     * 团队 | 发起培训 | 发起问卷 查询 机构结构接口 - 小程序
     */
    @Operation(summary = "团队修改后接口")
    @PostMapping("/getTeamDataByDeptId")
    public AjaxResult getTeamDataByDeptId(@RequestParam(required = false) Long deptId, @RequestParam(required = false) String nickName) {
        AjaxResult ajax = new AjaxResult();
        List<SysDept> deptList = new ArrayList<>();
        if (ObjectUtils.isEmpty(deptId)) {//查询当前顶级部门(parentId=0)和顶级部门下的列表
            Long userId = SecurityUtils.getUserId();
            SysUser sysUser = new SysUser();
            R<SysUser> result = userService.selectUserById(userId, SecurityConstants.INNER);
            if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                sysUser = result.getData();
            }
            Long currtDeptId = sysUser.getDeptId();
            if (StringUtils.isEmpty(nickName)) {
                R<List<SysDept>> resultDept = deptService.selectDeptList(new SysDept(), SecurityConstants.INNER);
                if (StringUtils.isNotNull(resultDept) && StringUtils.isNotNull(resultDept.getData())) {
                    deptList = resultDept.getData();
                }
            }
            if (deptList.size() > 0) {//移除自己部门
                deptList.remove(0);
                for (SysDept dept : deptList) {
//                    Integer count = userService.queryCountByDeptId(dept.getDeptId());
                    SysUser user = new SysUser();
                    user.setDeptId(dept.getDeptId());
                    R<List<SysUser>> resultList = userService.selectUserList(user, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(resultList) && StringUtils.isNotNull(resultList.getData())) {
                        dept.setCount(resultList.getData().size());
                    } else {
                        dept.setCount(0);
                    }
                }
            }
            //查询用户列表 selectUserById
            List<SysUser> userList = new ArrayList<>();
            R<List<SysUser>> resultUserList = userService.queryUserListByDeptId(currtDeptId, nickName, SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultUserList) && StringUtils.isNotNull(resultUserList.getData())) {
                userList = resultUserList.getData();
            }
            setRoleAndPost(userList);
            //封装用户列表的角色+岗位
            ajax.put("deptList", deptList);
            ajax.put("userList", userList);
            return AjaxResult.success(ajax);
        } else {
            if (StringUtils.isEmpty(nickName)) {
                R<List<SysDept>> result = deptService.getChildDeptListById(deptId, SecurityConstants.INNER);
                if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                    deptList = result.getData();
                }
            }
            if (deptList.size() > 0) {
                for (SysDept dept : deptList) {
                    //Integer count = userService.queryCountByDeptId(dept.getDeptId());
                    SysUser user = new SysUser();
                    user.setDeptId(dept.getDeptId());
                    R<List<SysUser>> resultList = userService.selectUserList(user, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(resultList) && StringUtils.isNotNull(resultList.getData())) {
                        dept.setCount(resultList.getData().size());
                    } else {
                        dept.setCount(0);
                    }
                }
            }
            //查询用户列表 selectUserById
            List<SysUser> userList = new ArrayList<>();
            R<List<SysUser>> resultUserList = userService.queryUserListByDeptId(deptId, nickName, SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultUserList) && StringUtils.isNotNull(resultUserList.getData())) {
                userList = resultUserList.getData();
            }
            setRoleAndPost(userList);
            ajax.put("deptList", deptList);
            ajax.put("userList", userList);
            return AjaxResult.success(ajax);
        }
    }

    private void setRoleAndPost(List<SysUser> userList) {
        if (null != userList && userList.size() > 0) {
            for (SysUser sysUser : userList) {
                Long userId = sysUser.getUserId();
                List<SysPostVO> postList = new ArrayList<>();
                R<List<SysPostVO>> result = postService.selectPostsByUserId(userId, SecurityConstants.INNER);
                if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                    postList = result.getData();
                }
                R<List<SysRole>> resultRoleList = roleMapper.selectRolePermissionByUserId(userId, SecurityConstants.INNER);
                if (StringUtils.isNotNull(resultRoleList) && StringUtils.isNotNull(resultRoleList.getData())) {
                    sysUser.setRoles(resultRoleList.getData());
                }
                List<Integer> sortList = postList.stream().map(SysPostVO::getPostSort).collect(Collectors.toList());
                sysUser.setSortList(sortList);
//                String deptIds = deptIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
                sysUser.setPostNames(postList.stream().map(SysPostVO::getPostName).collect(Collectors.joining(",")));
            }
        }
    }

    /**
     * 查询当前登录用户Id，被沟通人用户id
     *
     * @param :currentUserId 当前登录用户id
     * @param :userId        被沟通人id
     */
    @PostMapping("/queryUserListByUserId")
    public AjaxResult queryUserListByUserId(@RequestParam Long currentUserId, @RequestParam Long userId) {
        SysDept currentDept = null;
        R<SysDept> result = deptService.selectSuperDeptList(currentUserId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            currentDept = result.getData();
        }
        SysDept dept = null;
        R<SysDept> resultDept = deptService.selectSuperDeptList(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultDept) && StringUtils.isNotNull(resultDept.getData())) {
            dept = resultDept.getData();
        }
        List<SysUser> userDTOList = new ArrayList<>();
        Set<Long> userIds = new HashSet<>();
        if (null != currentDept && null != dept) {
            List<String> currentAncestors = Arrays.stream(currentDept.getAncestors().split(",")).collect(Collectors.toList());
            currentAncestors.add(currentDept.getDeptId().toString());
            List<String> ancestors = Arrays.stream(dept.getAncestors().split(",")).collect(Collectors.toList());
            ancestors.add(dept.getDeptId().toString());
            for (String deptId : ancestors) {
                if (!currentAncestors.contains(deptId)) {
                    SysDept sysDept = new SysDept();
                    R<SysDept> resultSysDept = deptService.getInfoById(Long.parseLong(deptId), SecurityConstants.INNER);
                    if (StringUtils.isNotNull(resultSysDept) && StringUtils.isNotNull(resultSysDept.getData())) {
                        sysDept = resultSysDept.getData();
                    }
                    if (!ObjectUtils.isEmpty(sysDept.getLeaderId()) && !userId.equals(sysDept.getLeaderId())) {
                        userIds.add(sysDept.getLeaderId());
                    }
                }
            }
            if (userIds.size() > 0) {
                for (Long id : userIds) {
                    SysUser sysUser = null;
                    R<SysUser> resultUser = userService.selectUserInfo(id, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(resultUser) && StringUtils.isNotNull(resultUser.getData())) {
                        sysUser = resultUser.getData();
                    }
                    if (null != sysUser) {
                        userDTOList.add(sysUser);
                    }
                }
            }


            return AjaxResult.success(userDTOList);
        }

        return AjaxResult.success(userDTOList);

    }

    //小程序获取当前用户的岗位列表
    @GetMapping("/getPostList/{userId}")
    public AjaxResult getPostList(@PathVariable Long userId) {
        Assert.notNull(userId, "用户id不能为空");
        List<SysPostVO> sysPostList = new ArrayList<>();
        R<List<SysPostVO>> result = postService.selectPostsByUserId(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            sysPostList = result.getData();
        }
        return AjaxResult.success(sysPostList);
    }


}
